package ngat.oss;

import ngat.message.OSS.*;
import ngat.util.*;
import ngat.util.logging.*;
import ngat.phase2.*; 
import ngat.instrument.*;
import ngat.phase2.nonpersist.*;

import dev.lt.*;

import java.io.*;
import java.util.*;

import jyd.dbms.*;
import jyd.storable.*;
import jyd.collection.*;

/**
 * Client: ADM / test version
 * Action: Sent by ADMIN to add a Proposal Stub. 
 * @author S.N.Fraser
 * $Id: ADD_PROPOSALImpl.java,v 1.1 2006/11/27 08:45:00 snf Exp $
 */

public class ADD_PROPOSALImpl extends TransactionImpl implements Logging {
    
    /** The path used to locate the Proposal in the OSS database. */
    protected Path     userPath;
    
    /** The Proposal to insert at 'userpath'.*/
    protected Proposal proposal;
    
    /** The password for this Proposal. */
    protected String   password;

    public ADD_PROPOSALImpl(Path userPath, Proposal proposal, String password) {
	super();
	this.userPath     = userPath;
	this.proposal     = proposal;	
	this.password     = password;
    }
    
    public ADD_PROPOSALImpl(ADD_PROPOSAL request) {
	super(request);
	this.userPath     = request.getUserPath();	
	this.proposal     = request.getProposal();
	this.password     = request.getPassword();
    }
    
    /**
     * Places the stub in the DB and updates the OSS password table..
     * @return Boolean or an OSS_Error.
     */
    public TRANSACTION_DONE exec() { 

	Logger logger = LogManager.getLogger("TRACE");
	
	
	User user = null;
	
	Transaction t = null;
	try {
	    t = Transaction.current();
	  
	    // Locate the Proposal's owner (PI) from its path expression.
	    user = OSS_Utilities.fetchUser(userPath);
	   
	    // Check the user exists.
	    if (user == null) {
		logger.log(ERROR, 3, "ADDPROPOSAL_impl", id, "exec", 
			   "User: "+userPath.toString()+" Not in database.");		
		return error(TRANSACTION.PATH_RESOLUTION_ERROR,
				     "Could not find PI user: "
				     +userPath.toString());
	    }

	    // Update the password table.
	    try {
		String userkey = userPath.toString()+"/"+proposal.getName();
		ServerContext.insertPasswordTableEntry(userkey, password);
		logger.log(1, "ADDPROPOSAL_Impl", id, "exec", 
			   "Inserted PWT entry for: "+userkey);
	    } catch (ServerEnvException sex) {
		logger.log(ERROR, 1, "ADDPROPOSAL_Impl", id, "exec", 
			   "Warning - Error Updating Password Table: "+sex);
		
		//return error(TRANSACTION.PASSWORD_TABLE_ERROR, 
		// "Password Table Update: "+sex);
	    }
	    
	    
	    // Slot the Proposal stub in.
	    user.addProposal(proposal.getName());

	    // Dont forget to unlock it!
	    proposal.setLastUnLocked(System.currentTimeMillis());
	    proposal.setLastEditor("TMC Admin/Stub Entry");

	    // Revision info.
	    //proposal.addRevisionInfo(System.currentTimeMillis(), 
	    //		     "OSS",
	    //		     0xCCAABBEEL,
	    //		     "TMC Stub entry");

	    logger.log(1, "ADDPROPOSALImpl", id, "exec",
		       "Updating Group Execution times:");
	    // Now Update the execution times for all Groups.
	    Group    group = null;
	    Iterator it    = proposal.listAllGroups();
	    while (it.hasNext()) {
		group = (Group)it.next();
		Scheduling.calculateExecutionTimes(group);
		logger.log(1, "ADDPROPOSALImpl", id, "exec",
			   "Group: "+group.getName()+
			   "\n\tMaximal: "+(group.getMaximalExecutionTime()/1000.0)+" secs."+
			   "\n\tNominal: "+(group.getNominalExecutionTime()/1000.0)+" secs."+
			   "\n\tSlewing: "+(group.getSlewTime()/1000.0)+" secs.");
		if (group instanceof FixedGroup) {
		    FixedGroup fg = (FixedGroup)group;
		    Scheduling.modifyFixedGroup(fg);
		    logger.log(1, "ADDPROPOSALImpl", id, "exec",
			       "Adding fixed group: "+fg.getName()+
			       " at "+sdf.format(new Date(fg.getFixedTime())));
		}
		
	    }
	    
	    // Store it.
	    try {
		OSS_Utilities.storeProposal(proposal);
	    } catch (IOException ix) {
		logger.log(1, "ADDPROPOSALImpl", id, "exec",
			   "Proposal ["+proposal.getFullPath()+
			   "] Unable to Store: "+ix);
		return error(TRANSACTION.DATABASE_UPDATE_ERROR, 
				     "Proposal ["+proposal.getFullPath()+
				     "] Unable to Store: "+ix);
	    }
	} finally {
	    t.commit();
	}

	ADD_PROPOSAL_DONE done = new ADD_PROPOSAL_DONE(id);
	done.setSuccessful(true);
	return done;

	// Send a message to the PI via SMTP.
	//new SMTPMailer(user.getEmail(), proposal, password);
	// Update was Ok.

    }
    
}

/** $Log: ADD_PROPOSALImpl.java,v $
/** Revision 1.1  2006/11/27 08:45:00  snf
/** Initial revision
/**
/** Revision 1.2  2001/04/27 17:22:00  snf
/** Adda proposal.
/**
/** Revision 1.1  2001/02/23 18:51:14  snf
/** Initial revision
/**
/** Revision 1.1  2001/02/19 16:41:21  snf
/** Initial revision
/**
/** Revision 1.2  2001/02/16 17:43:10  snf
/** *** empty log message ***
/**
/** Revision 1.1  2000/12/12 18:18:32  snf
/** Initial revision
/** */
